package org.brisling.service.common;

import java.util.ArrayList;
import java.util.List;

import org.brisling.domain.common.ListDomain;
import org.brisling.domain.sysman.inf.BizBeanDataModeler;
import org.brisling.repository.inf.ListByUpLinkRepository;
import org.brisling.util.JsonUtil;
import org.brisling.util.LongUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

public class BaseListByUplinkService{

	//定义起始页是否为1
	private Boolean pageBasedOne=false;
	
	
	public <T extends BizBeanDataModeler> List<T> getAll(ListByUpLinkRepository<T,Long> repo){
		
		Iterable<T> ite = repo.findAll();
		
		if(ite instanceof List) {
			return (List<T>) ite;
		}
		ArrayList<T> list = new ArrayList<T>();
		if(ite != null) {
			for(T t: ite) {
			    list.add(t);
			}
		}
		return list;		
	}
	
	public <T extends BizBeanDataModeler> ListDomain<T> getPagedListByUplinkid(String uplinkid,String page,String pageSize,
			ListByUpLinkRepository<T,Long> repo){
		
		Integer _uplinkid = LongUtil.getIntValue(uplinkid, null);
		Integer _page = LongUtil.getIntValue(page, 0);
		Integer _pageSize = LongUtil.getIntValue(pageSize, 10);
		
		
		ListDomain<T> listDomain = new ListDomain<T>();
		//dept为空，返回空值对象
		if(_uplinkid==null){
			listDomain.setTotal(0l);
			listDomain.setRows(new ArrayList<T>());
			return listDomain;
		}
	
		if(!pageBasedOne)
			_page -= 1;
		
		PageRequest _pageRequest = 
				new PageRequest(_page,_pageSize,new Sort(new String[] { "sortedid" }));
		
		Long _total = repo.countByUplinkid(new Long(_uplinkid));
		List<T> _usrList = repo.findByUplinkid(new Long(_uplinkid), _pageRequest);		
		
		listDomain.setTotal(_total);
		listDomain.setRows(_usrList);
		
		return listDomain;
		
	}
	
	public <T extends BizBeanDataModeler> T save(ListByUpLinkRepository<T,Long> repo,T t){
		return (T) repo.save(t);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String del(ListByUpLinkRepository repo,Long id){
		repo.delete(id);
		return "success";
	}
	
	public <T extends BizBeanDataModeler> T  bodyToObj (String body,Class<T> clazz){
		
		return JsonUtil.bodyToObj(body, clazz);
	}
	
	
}
